<template>
  <div class="content">
    <div class="flex flex-justify-between questionContent">
      <div class="question_content w60">
        <div class="expand flex flex-align-center flex-justify-center cursor_pointer"
          @click="if_analysis = !if_analysis" :class="{ expanded: if_analysis }" v-if="!realState">
          <img src="@/assets/img/analysis.png" alt="" class="analysisIcon" v-if="if_analysis == false">
          <div v-if="if_analysis == false">解析</div>
          <div v-else class="flex flex-align-center">
            <el-icon>
              <DArrowRight />
            </el-icon>
            <div>收起</div>
          </div>
        </div>
        <div class="flex" v-if="currentQuestion">
          <div class="questionType" v-if="currentQuestion.type < 3">
            {{
              currentQuestion.type == '1' ? '单选' : currentQuestion.type == '2' ? '判断' : '多选'
            }}
          </div>
          <!-- <div class="rules marL10" v-if="currentQuestion.newTg == 1">新题规</div> -->
          <div class="marL10 title">{{ currentQuestion.title }}</div>
        </div>
        <div class="flex">
          <div style="width: 45%;">
            <div v-for="(item, i) in currentQuestion?.options || []" :key="i">
              <div class="flex marT50 cursor_pointer" @click="optionFun(i, item.option)" v-if="item.name">
                <div class="w90 flex flex-align-center flex-justify-center">
                  <!-- 学习模式下所有正确选项都显示对号 -->
                  <template v-if="realState">
                    <div class="option-true" v-if="currentQuestion.answer.includes(item.option)">
                      <el-icon><Select /></el-icon>
                    </div>
                    <div class="option-num" v-else>{{ item.option }}</div>
                  </template>
                  <template v-else>
                    <!-- 多选（type=='0'） -->
                    <template v-if="currentQuestion.type == '0'">
                      <!-- 已确认：错误优先显示红叉，正确显示对勾，其余显示字母 -->
                      <template v-if="hasConfirmed">
                        <div class="option-false" v-if="wrongSelectedOptions.includes(item.option)">
                          <el-icon>
                            <CloseBold />
                          </el-icon>
                        </div>
                        <div class="option-true"
                          v-else-if="currentQuestion.answer.includes(item.option) && selectedOptions.includes(item.option)">
                          <el-icon><Select /></el-icon>
                        </div>
                        <div class="option-num option-true"
                          v-else-if="currentQuestion.answer.includes(item.option) && !selectedOptions.includes(item.option)">
                          {{ item.option }}
                        </div>
                        <div class="option-num" v-else>{{ item.option }}</div>
                      </template>
                      <!-- 未确认：仅已选中显示对勾，未选显示字母 -->
                      <template v-else>
                        <div class="option-true" v-if="selectedOptions.includes(item.option)">
                          <el-icon><Select /></el-icon>
                        </div>
                        <div class="option-num" v-else>{{ item.option }}</div>
                      </template>
                    </template>
                    <!-- 单选/判断：原逻辑 -->
                    <template v-else>
                      <div class="option-true"
                        v-if="optionTab == i && currentQuestion.answer == currentQuestion.answered">
                        <el-icon><Select /></el-icon>
                      </div>
                      <div class="option-false"
                        v-else-if="optionTab == i && currentQuestion.answer != currentQuestion.answered">
                        <el-icon>
                          <CloseBold />
                        </el-icon>
                      </div>
                      <!-- 答错时显示正确选项 -->
                      <div class="option-true"
                        v-else-if="currentQuestion.answered && currentQuestion.answer === item.option && currentQuestion.answer != currentQuestion.answered">
                        <el-icon><Select /></el-icon>
                      </div>
                      <div class="option-num" v-else>{{ item.option }}</div>
                    </template>
                  </template>
                </div>
                <div class="marL10 f28" :class="currentQuestion.type == '0'
                  ? (hasConfirmed
                    ? (wrongSelectedOptions.includes(item.option)
                      ? 'errorFont'
                      : (currentQuestion.answer.includes(item.option) ? 'successFont' : ''))
                    : (selectedOptions.includes(item.option) ? 'successFont' : ''))
                  : (realState
                    ? (currentQuestion.answer === item.option ? 'successFont' : '')
                    : (optionTab == i
                      ? currentQuestion.answer == currentQuestion.answered
                        ? 'successFont'
                        : 'errorFont'
                      : (currentQuestion.answered && currentQuestion.answer === item.option ? 'successFont' : '')))
                  ">
                  {{ item.name }}
                </div>
              </div>
            </div>
            <div class="unmultiple" v-if="currentQuestion && currentQuestion.type == '0' && !realState && !hasConfirmed"
              @click="confirmMultipleChoice" :class="{ 'multipled': selectedOptions.length > 0 }">
              确认
            </div>
          </div>
          <div v-if="currentQuestion && currentQuestion.img && if_analysis" class="tipsImgs">
            <el-image :src="currentQuestion.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
              :preview-src-list="[currentQuestion.img]" show-progress :initial-index="4" fit="cover"
              :hide-on-click-modal="true" />
            <p>点击图片查看大图</p>
          </div>
        </div>
      </div>
      <div v-if="currentQuestion && currentQuestion.img && !if_analysis" class="tipsImg" style="width: 40%;">
        <el-image :src="currentQuestion.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
          :preview-src-list="[currentQuestion.img]" show-progress :initial-index="4" fit="cover"
          :hide-on-click-modal="true" />
        <p>点击图片查看大图</p>
      </div>
      <!-- 解析 -->
      <div class="analysis" v-if="if_analysis == true">
        <div class="back-to-top flex flex-align-center flex-justify-center" v-show="showBackToTop" @click="scrollToTop">
          <el-icon size="30">
            <Top />
          </el-icon>
        </div>
        <div class="analysis_content">
          <div class="analysis_header">
            <div class="correct_answer flex flex-align-center flex-justify-between">
              <div>
                <span class="answer_title">正确答案：</span>
                <span class="answer_option">{{ currentQuestion.answer }}</span>
              </div>
              <!-- <div class="correction">纠错</div> -->
            </div>
          </div>
          <div class="gap"></div>
          <div class="suji">
            <div class="flex flex-align-center">
              <div class="line"></div>
              <div class="marL10 analysis_title">速记口诀</div>
            </div>
            <div class="cont">
              <p>{{ currentQuestion.fastStudy }}</p>
              <!-- <div class="bg"></div> -->
              <!-- <div class="check">查看完整技巧</div> -->
            </div>
          </div>
          <div class="gap"></div>
          <div class="suji">
            <div class="flex flex-align-center">
              <div class="line"></div>
              <div class="marL10 analysis_title">题目解析</div>
            </div>
            <div class="analysis_item">
              {{ currentQuestion.questionAnalysis }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部题库 -->
    <div class="question_bank">
      <div class="flex flex-align-center flex-justify-between use">
        <div class="flex flex-align-center">
          <div class="cursor_pointer" @click="previousQuestion"
            :class="currentQuestionIndex == 0 ? 'boundary_button' : 'default_button'">
            上一题
          </div>
          <div class="marL40 cursor_pointer" @click="nextQuestion" :class="currentQuestionIndex == optionList.length - 1 ? 'boundary_button' : 'default_button'
            ">
            下一题
          </div>
          <div class="flex flex-align-center marL80 cursor_pointer" @click="questionDrawer = !questionDrawer">
            <div class="true_icon">
              <el-icon><Select /></el-icon>
            </div>
            <div class="marL15 f30">{{ correct }}</div>
            <div class="false_icon marL40">
              <el-icon>
                <CloseBold />
              </el-icon>
            </div>
            <div class="marL15 f30">{{ wrongNum }}</div>
            <img src="../../assets/img/num.jpg" alt="" class="pic35 marL40" />
            <div class="f30 marL15">
              {{ (currentQuestionIndex ?? 0) + 1 }}/{{ optionList.length }}
            </div>
          </div>
        </div>
        <div class="flex">
          <div class="marR20">
            <div class="f30 flex flex-align-center" @click="openLearnMode">
              <img :src="realState ? select : unselected" alt="" class="iconImg cursor_pointer">
              <div class="marL10">开启学习模式</div>
            </div>
            <div class="flex flex-align-center marT30">
              <div class="f30 flex flex-align-center cursor_pointer" @click="readQuestion">
                <img :src="isplay ? read : unread" alt="" class="iconImg">
                <div class="marL10" :class="isplay ? 'reading' : ''">读题</div>
              </div>
              <div class="f30 marL30 flex flex-align-center cursor_pointer" @click="saveQuestionData('1')">
                <el-icon v-if="currentQuestion && !currentQuestion.isCollected">
                  <Star />
                </el-icon>
                <el-icon color="#fed701" size="40" v-else>
                  <StarFilled />
                </el-icon>
                <div class="marL10">
                  {{ currentQuestion && !currentQuestion.isCollected ? '收藏' : '已收藏' }}
                </div>
              </div>
              <div class="f30 flex flex-align-center marL30">
                <img src="@/assets/img/setting.png" alt="" class="iconImg cursor_pointer">
                <div class="marL10">设置</div>
              </div>
            </div>
          </div>
          <div class="downloadInfo flex flex-justify-center flex-align-center marL20">
            <img src="@/assets/img/ewm.png" alt="" class="downloadImg">
            <div class="download">下载手机版</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 题库抽屉 -->
    <el-drawer v-model="questionDrawer" :direction="questionDirection" :before-close="questionClose"
      class="question-drawer" size="37.5rem" :modal="true" :modal-class="'transparent-drawer-overlay'">
      <div class="flex flex-align-center flex-justify-between use">
        <div class="flex flex-align-center">
          <div class="cursor_pointer" @click="previousQuestion"
            :class="currentQuestionIndex == 0 ? 'boundary_button' : 'default_button'">
            上一题
          </div>
          <div class="marL40 cursor_pointer" @click="nextQuestion" :class="currentQuestionIndex == optionList.length - 1 ? 'boundary_button' : 'default_button'
            ">
            下一题
          </div>
          <div class="flex flex-align-center marL80 cursor_pointer" @click="upPull">
            <div class="true_icon">
              <el-icon><Select /></el-icon>
            </div>
            <div class="marL15 f30">{{ correct }}</div>
            <div class="false_icon marL40">
              <el-icon>
                <CloseBold />
              </el-icon>
            </div>
            <div class="marL15 f30">{{ wrongNum }}</div>
            <img src="../../assets/img/num.jpg" alt="" class="pic35 marL40" />
            <div class="f30 marL15">
              {{ (currentQuestionIndex ?? 0) + 1 }}/{{ optionList.length }}
            </div>
          </div>
        </div>
        <div class="flex">
          <div class="marR20">
            <div class="f30 flex flex-align-center" @click="openLearnMode">
              <img :src="realState ? select : unselected" alt="" class="iconImg cursor_pointer">
              <div class="marL10">开启学习模式</div>
            </div>
            <div class="flex flex-align-center marT30">
              <div class="f30 flex flex-align-center cursor_pointer" @click="readQuestion">
                <img :src="isplay ? read : unread" alt="" class="iconImg">
                <div class="marL10" :class="isplay ? 'reading' : ''">读题</div>
              </div>
              <div class="f30 marL30 flex flex-align-center cursor_pointer" @click="saveQuestionData('1')">
                <el-icon v-if="currentQuestion && !currentQuestion.isCollected">
                  <Star />
                </el-icon>
                <el-icon color="#fed701" size="40" v-else>
                  <StarFilled />
                </el-icon>
                <div class="marL10">
                  {{ currentQuestion && !currentQuestion.isCollected ? '收藏' : '已收藏' }}
                </div>
              </div>
              <div class="f30 flex flex-align-center marL30">
                <img src="@/assets/img/setting.png" alt="" class="iconImg cursor_pointer">
                <div class="marL10">设置</div>
              </div>
            </div>
          </div>
          <div class="downloadInfo flex flex-justify-center flex-align-center marL20">
            <img src="@/assets/img/ewm.png" alt="" class="downloadImg">
            <div class="download">下载手机版</div>
          </div>
        </div>
      </div>
      <div class="tips">
        <div class="flex flex-align-center flex-justify-between">
          <div class="font40">答题卡</div>
          <div class="clearRecord cursor_pointer" @click="clearRecord">清除记录</div>
        </div>
        <div class="list marT20">
          <div class="list_item cursor_pointer" v-for="(item, index) in optionList" :key="index" :class="{
            active: currentQuestionIndex === index,
            success: item.answer == item.answered,
            wrong_bg:
              item.answer != item.answered && item.answered != null && item.answered != '',
          }" @click="gotoQuestion(index)">
            {{ index + 1 }}
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog v-model="clearModel" width="55%" :before-close="handleClose" :close-on-click-modal="false"
      :style="{ borderRadius: '10px', paddingBottom: '40px' }">
      <div class="prompt">温馨提示</div>
      <div class="f35">您确定要清空当前做题记录并重新开始吗？</div>
      <template #footer>
        <div class="dialog-footer flex flex-align-center flex-justify-center">
          <div @click="clearModel = false" class="cancel">取消</div>
          <div @click="confrim" class="sure marL30">清空</div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, onMounted, onUnmounted, watch } from 'vue'
import type { DrawerProps } from 'element-plus'
import { Select, CloseBold, DArrowRight, Top, Star, StarFilled } from '@element-plus/icons-vue'
import './index.scss'
import { questionBank, getQuestionProgress, getSpecialQuestion, getSpeechSynthesis } from '@/api/userApi'
import { ElLoading, ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { useRoute } from 'vue-router'
import unselected from '@/assets/img/unselected.png'
import select from '@/assets/img/select.png'
import read from '@/assets/img/read.png'
import unread from '@/assets/img/unread.png'

const realState = ref(false)

const route = useRoute()
const userStore = useUserStore()
const questionState = ref(route.query.status) //判断题型状态
console.log(questionState.value, "questionState==");


// 修正为合法的 DrawerProps['direction'] 值，'btt' 表示 bottom to top
const questionDirection = ref<DrawerProps['direction']>('btt')
const currentQuestionIndex = ref()
// 选择题其中哪一项
const optionTab = ref(-1)
const isSelect = ref(false)
// 多选：临时选中项
const selectedOptions = ref<string[]>([])
// 多选：确认后标记为错误的已选项
const wrongSelectedOptions = ref<string[]>([])
// 多选：本题是否已确认（已确认后不可再改）
const hasConfirmed = ref(false)
//判断答对是否自动跳转下一题
const if_click = ref(1)
const clearModel = ref(false)
const questionDrawer = ref(false)
// 判断显示隐藏解析
const if_analysis = ref(false)
const handleClose = () => {
  clearModel.value = false
}

const correct = computed(
  () => optionList.value.filter((q) => q.answered && q.answered === q.answer).length,
)
const wrongNum = computed(
  () => optionList.value.filter((q) => q.answered && q.answered !== q.answer).length,
)

interface Question {
  questionId: string // 或 number
  title: string
  answer: string
  answered: string
  type: string
  img: string
  questionAnalysis: string
  isCorrect: number
  isCollected: number
  fastStudy: string
  options: any[]
  userAnswer: string
}
const optionList = ref<Question[]>([])
const currentQuestion = computed<any | undefined>(() => {
  return optionList.value[currentQuestionIndex.value]
})
console.log(currentQuestion, 'currentQuestion')

const optionFun = (index: number, ele: any) => {
  // 多选(type=='0')：未确认前可切换
  if (currentQuestion.value?.type == '0') {
    if (hasConfirmed.value) return
    const pos = selectedOptions.value.indexOf(ele)
    if (pos > -1) {
      selectedOptions.value.splice(pos, 1)
    } else {
      selectedOptions.value.push(ele)
    }
    return
  }
  if (!isSelect.value) {
    optionTab.value = index
    currentQuestion.value.answered = ele
    if (currentQuestion.value.answered == currentQuestion.value.answer && if_click.value == 1) {
      setTimeout(() => {
        nextQuestion()
      }, 100)
    } else if (currentQuestion.value.answered !== currentQuestion.value.answer) {
      if_analysis.value = true
    }
  }
  isSelect.value = true
}
const checkAnswer = () => {
  let seleteValue = currentQuestion.value.answered
  if (seleteValue) {
    if (currentQuestion.value.type == '0') {
      const picked = seleteValue.split('').filter((ch: string) => /[A-D]/.test(ch))
      selectedOptions.value = picked
      const correct = currentQuestion.value.answer.split('')
      wrongSelectedOptions.value = picked.filter((op: any) => !correct.includes(op))
      hasConfirmed.value = true
      isSelect.value = true
    } else {
      currentQuestion.value.options.forEach((item: any, index: number) => {
        if (item.option == seleteValue) {
          optionTab.value = index
          isSelect.value = true
        }
      })
    }
  } else {
    optionTab.value = -1
    isSelect.value = false
    selectedOptions.value = []
    wrongSelectedOptions.value = []
    hasConfirmed.value = false
  }
}
const nextQuestion = () => {
  if (currentQuestionIndex.value < optionList.value.length - 1) {
    optionTab.value = -1
    isSelect.value = false
    selectedOptions.value = []
    wrongSelectedOptions.value = []
    hasConfirmed.value = false
    currentQuestionIndex.value++
    if (!realState.value) {
      if_analysis.value = false
    }
    checkAnswer()
    stopAudio()
  }
}
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    optionTab.value = -1
    isSelect.value = false
    selectedOptions.value = []
    wrongSelectedOptions.value = []
    hasConfirmed.value = false
    if (!realState.value) {
      if_analysis.value = false
    }
    checkAnswer()
    stopAudio()
  }
}
const upPull = () => {
  questionDrawer.value = !questionDrawer.value
}
const gotoQuestion = (index: number) => {
  currentQuestionIndex.value = index
  optionTab.value = -1
  selectedOptions.value = []
  wrongSelectedOptions.value = []
  hasConfirmed.value = false
  checkAnswer()
  stopAudio()
}
const clearRecord = () => {
  clearModel.value = true
}
const confrim = async () => {
  currentQuestionIndex.value = 0
  optionTab.value = -1
  isSelect.value = false
  selectedOptions.value = []
  wrongSelectedOptions.value = []
  hasConfirmed.value = false
  const obj = {
    memberId: userStore.storeInfo.memberId,
    carModelId: userStore.storeInfo.carModelId,
    categoryId: userStore.categoryId,
    isSimulation: 0,
    answerRecords: [] as Array<{
      questionId: string
      userAnswer: string
      isCorrect: number
      isCollected: number
    }>,
  }
  const answerSummary = optionList.value
    .filter((q) => q.answered)
    .map((q) => {
      return {
        questionId: q.questionId,
        userAnswer: '',
        isCorrect: q.answered === q.answer ? 1 : 0,
        isCollected: 0,
      }
    })
  obj.answerRecords = answerSummary
  try {
    const res = await getQuestionProgress(obj)
    if (res.code === '00000') {
      optionList.value
        .filter((q) => q.answered)
        .forEach((item) => {
          item.answered = ''
          item.isCollected = 0
        })
      ElMessage.success('答题清空成功')
    }
  } catch {
  } finally {
  }
  questionDrawer.value = false
  clearModel.value = false
}
const questionClose = () => {
  questionDrawer.value = false
}

const showBackToTop = ref(false)

const handleScroll = () => {
  const scrollContainer = document.querySelector('.analysis') || document.documentElement
  const scrollY = scrollContainer.scrollTop || window.scrollY
  showBackToTop.value = scrollY > 100
}

const scrollToTop = () => {
  const scrollContainer = document.querySelector('.analysis') || window
  scrollContainer.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}

const confirmMultipleChoice = () => {
  if (currentQuestion.value?.type != '0') return
  if (selectedOptions.value.length === 0) {
    ElMessage.warning('请至少选择一个选项')
    return
  }
  const picked = [...selectedOptions.value].sort()
  const correct = currentQuestion.value.answer.split('').sort()
  wrongSelectedOptions.value = picked.filter(op => !correct.includes(op))
  currentQuestion.value.answered = picked.join('')
  hasConfirmed.value = true
  if (picked.join('') === correct.join('') && if_click.value == 1) {
    setTimeout(() => {
      nextQuestion()
    }, 100)
  } else {
    if_analysis.value = true
  }
}

const getQuestionList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
  })
  try {
    let obj = {
      carModelId: userStore.storeInfo.carModelId,
      categoryId: userStore.categoryId,
      id: userStore.storeInfo.memberId,
      queryType: '03',
      groupId: route.query.id,
      ...(questionState.value === '1' ? { questionType: Number(route.query.questionType) } : {}),
      ...(questionState.value === '2' ? { isAnswer: route.query.isAnswer } : {}),
    }
    const res = (questionState.value === '1' || questionState.value === '2')
      ? await questionBank(obj)
      : await getSpecialQuestion(obj)
    if (res.code === '00000') {
      const mapQuestion = (e: any) => ({
        title: e.questionName,
        type: e.questionType,
        img: e.questionImg,
        options: [
          { option: 'A', name: e.questionA },
          { option: 'B', name: e.questionB },
          { option: 'C', name: e.questionC },
          { option: 'D', name: e.questionD },
        ],
        answer: e.answer,
        answered: '',
        fastStudy: e.fastStudy,
        questionAnalysis: e.questionAnalysis,
        questionId: e.id,
        isCorrect: e.isCorrect,
        isCollected: e.isCollected,
        originalIsCollected: e.isCollected
      })

      let wxQuestionS = []
      if (questionState.value === '1' || questionState.value === '2') {
        wxQuestionS = res.data[0]?.wxQuestionS || []
      } else {
        wxQuestionS = res.data?.wxQuestionS || []
      }
      optionList.value = wxQuestionS.map(mapQuestion)
      const index = optionList.value?.reduce((lastIndex, current, currentIndex) => {
        return current.answered ? currentIndex : lastIndex
      }, -1)
      currentQuestionIndex.value = index == -1 ? 0 : index

      if (currentQuestion.value?.type == '0') {
        checkAnswer()
      } else {
        currentQuestion.value?.options.forEach((item: any, index: number) => {
          if (item.option == currentQuestion.value.answered) {
            optionTab.value = index
            isSelect.value = true
          }
        })
      }
    }
  } finally {
    loading.close()
  }
}

// 只保存用户本次操作过的数据（即本次进入页面后操作过的题目），之前做的数据不保存
const operatedQuestions = ref<Set<string>>(new Set())

// 在用户答题或收藏时调用此方法记录操作过的题目
const markQuestionOperated = (questionId: string) => {
  operatedQuestions.value.add(questionId)
}

const saveQuestionData = async (e: any) => {
  if (e) currentQuestion.value.isCollected = !currentQuestion.value.isCollected //e参数判断是否为收藏的时候保存数据
  // 只保存本次操作过的题目数据
  if (!optionList.value || !optionList.value.length) return;
  console.log(currentQuestion.value.questionId, "currentQuestion.value.questionId===");

  markQuestionOperated(currentQuestion.value.questionId)
  const answerRecords: Array<{
    questionId: string
    userAnswer: string
    isCorrect: number
    isCollected: number
  }> = []

  optionList.value.forEach((q: any) => {
    if (
      operatedQuestions.value.has(q.questionId) // 只保存本次操作且已作答的题
    ) {
      let currentCollect
      if (q.originalIsCollected && !q.isCollected) {
        currentCollect = 2
      } else {
        currentCollect = q.isCollected ? 1 : 0
      }
      answerRecords.push({
        questionId: q.questionId,
        userAnswer: q.answered,
        isCorrect: q.answered === q.answer ? 1 : 0,
        isCollected: currentCollect,
      })
    }
  })

  console.log(answerRecords, "answerRecords===");

  if (answerRecords.length === 0) return
  const obj = {
    memberId: userStore.storeInfo.memberId,
    carModelId: userStore.storeInfo.carModelId,
    categoryId: userStore.categoryId,
    isSimulation: 0,
    answerRecords,
  }

  try {
    const res = await getQuestionProgress(obj)
    if (res.code === '00000' && !e) {
      // ElMessage.success('顺序练习记录保存成功')
    }
  } catch {
  } finally {
  }
}

const openLearnMode = () => {
  realState.value = !realState.value
  if (realState.value) {
    if_analysis.value = true
  } else {
    if_analysis.value = false
  }
}

// 读题功能实现
const tempAudio = ref()
const isplay = ref(false)
const audioMap = ref<any>({})
const audioUrl = ref('')

function stopAudio() {
  if (tempAudio.value) {
    tempAudio.value.pause()
    tempAudio.value = null
  }
  audioUrl.value = ''
  audioMap.value = {}
  isplay.value = false
}

watch(currentQuestionIndex, () => {
  stopAudio()
})

const getSpeechData = async () => {
  if (!currentQuestion.value) return
  const res = await getSpeechSynthesis({
    text: currentQuestion.value.title,
    volume: 0,
    speed: 0,
    voiceType: 0
  })
  if (res.code === '00000' && res.data && res.data.audio) {
    let base64 = res.data.audio
    let mimeType = 'audio/wav'
    if (typeof base64 === 'string') {
      const match = base64.match(/^data:(audio\/\w+);base64,(.*)$/)
      if (match) {
        mimeType = match[1]
        base64 = match[2]
      }
      const byteCharacters = atob(base64)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: mimeType })
      const tempUrl = URL.createObjectURL(blob)
      tempAudio.value = new Audio(tempUrl)
      tempAudio.value.onended = () => {
        isplay.value = false
      }
      tempAudio.value.onpause = () => {
        isplay.value = false
      }
      tempAudio.value.onplay = () => {
        isplay.value = true
      }
      tempAudio.value.play()
      audioUrl.value = tempUrl
      audioMap.value = { url: tempUrl }
    } else {
      return
    }
  }
}

const readQuestion = async () => {
  if (isplay.value) {
    if (tempAudio.value) {
      tempAudio.value.pause()
    }
    isplay.value = false
  } else {
    isplay.value = true
    await getSpeechData()
  }
}

onMounted(async () => {
  const scrollContainer = document.querySelector('.analysis') || window
  scrollContainer.addEventListener('scroll', handleScroll)
  handleScroll() // 初始检查
  await getQuestionList()
  console.log(currentQuestionIndex.value, 'currentQuestionIndex===')
})

onUnmounted(() => {
  const scrollContainer = document.querySelector('.analysis') || window
  scrollContainer.removeEventListener('scroll', handleScroll)
  saveQuestionData('')
  stopAudio()
})
</script>
<style scoped lang="scss">
@use './order.scss' as *;

:deep(.question-drawer) {
  .el-drawer {
    height: 900px !important;
  }

  .el-drawer__body {
    height: 100%;
    padding: 0;
    // overflow: hidden;
  }
}

:deep(.transparent-drawer-overlay) {
  background-color: transparent !important;
}
</style>
